// pages/shiye/subpages/report/report.ts
import type { ChatList } from "../../../../typings/types/shiye/index";
import { arrayBufferToString } from "../../../utils/baseutf";
import { marked } from "../../../miniprogram_npm/marked/lib/marked.esm";
import { zcc } from "../../../utils/util";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    visible: false, //设置菜单弹框是否显示
    inputValue: "", //当前输入框输入的问题
    chatList: [] as ChatList,
    contentItems: "", ////当前正在输出的数据流(markdown格式)
    isRegenerate: false, //是否重新生成
    preInputValue: "", //上一次查询输入内容,用于重新生成使用
    isLoading: false, //节流loading
    loadingStatus: false, //加载状态显示loading,当loadingStatus为true,不用展示"正在思考"状态
    requestTask: null as WechatMiniprogram.RequestTask | null,
    scrollTopShow: false,
    scrollBottomShow: false,
    lt: "<",
    gt: ">",
    copyIndex: 0, //复制的索引(chatList中的index)
    copyText: "",
    currentHTML: "",
    currentThinkHTML: "",
    currentAnswerHTML: "",
    scrollTop: 0,
    isRolling: false, //鼠标滚轮是否滚动
    isBottom: true, //滚动参数
    titleStr: "尽调报告",
    baseUrl: "https://shiye.bczcc.com",
    inputBoxBottom: 0,
  },
  showThinkFn(e: any) {
    const index = e.target.dataset.index;
    const answerIndex = e.target.dataset.answerindex;
    const showThinkList =
      "chatList[" + index + "].showThinkList[" + answerIndex + "]";
    this.setData({
      [showThinkList]: true,
    });
  },
  hideThinkFn(e: any) {
    const index = e.target.dataset.index;
    const answerIndex = e.target.dataset.answerindex;
    const showThinkList =
      "chatList[" + index + "].showThinkList[" + answerIndex + "]";
    this.setData({
      [showThinkList]: false,
    });
  },
  //滚动事件
  onScroll(e: any) {
    const query = wx.createSelectorQuery();
    // 选择元素
    query.select("#scrollElement").boundingClientRect();

    // 执行查询
    query.exec((res) => {
      if (res && res[0]) {
        const offsetHeight = res[0].height; // 获取元素的高度（相当于 offsetHeight）
        if (e.detail.scrollHeight - e.detail.scrollTop - offsetHeight < 40) {
          this.setData({
            isBottom: true,
            scrollBottomShow: false,
          });
        } else {
          this.setData({
            isBottom: false,
            scrollBottomShow: true,
          });
        }
      }
    });
    if (e.detail.scrollTop < 5) {
      this.setData({
        scrollTopShow: false,
      });
    } else {
      this.setData({
        scrollTopShow: true,
      });
    }
  },
  //下载尽调报告
  downloadReport(e: any) {
    const url = e.target.dataset.url;
    // const url =
    //   "https://files.bczcc.com/prompt/尽调报告_江苏省建筑工程集团有限公司_55_20250208_170139.docx";
    wx.downloadFile({
      url: url,
      success: function (res) {
        if (res.statusCode === 200) {
          const filePath = res.tempFilePath;
          wx.openDocument({
            filePath: filePath,
            showMenu: true, //默认是false，为true的时候，右上角有三个点
            success: function () {
              console.log("打开文档成功");
            },
            fail: function (err) {
              console.log("打开文档失败", err);
            },
          });
        }
      },
      fail: function (err) {
        console.log("下载文件失败", err);
      },
    });
  },
  //复制
  copyFn(e: any) {
    const index = e.target.dataset.index;
    const answerIndex = e.target.dataset.answerindex;
    this.setData({
      copyIndex: index,
      copyText: this.data.chatList[index].downMessage[answerIndex]
        .replace("<sy_think>", "")
        .replace("</sy_think>", ""),
    });
    wx.setClipboardData({
      data: this.data.copyText,
      success: function () {
        wx.showToast({
          title: "复制成功",
          icon: "none",
        });
      },
      fail: function () {
        wx.showToast({
          title: "复制失败",
          icon: "none",
        });
      },
    });
  },
  //重新生成
  regenerateFn() {
    this.setData({
      isRegenerate: true,
    });
    this.requestFn();
  },
  //上一页
  preFn(e: any) {
    const index = e.target.dataset.index;
    const answerIndex = e.target.dataset.answerindex;
    if (this.data.isLoading)
      return wx.showToast({
        title: "正在生成内容,请勿切换。",
        icon: "none",
      });
    const curAnswerIndex = "chatList[" + index + "].answerIndex";
    if (answerIndex === 0) {
      this.setData({
        [curAnswerIndex]: this.data.chatList[index].message.length - 1,
      });
    } else {
      this.setData({
        [curAnswerIndex]: this.data.chatList[index].answerIndex - 1,
      });
    }
  },
  //下一页
  nextFn(e: any) {
    const index = e.target.dataset.index;
    const answerIndex = e.target.dataset.answerindex;
    if (this.data.isLoading)
      return wx.showToast({
        title: "正在生成内容,请勿切换。",
        icon: "none",
      });
    const curAnswerIndex = "chatList[" + index + "].answerIndex";
    if (answerIndex === this.data.chatList[index].message.length - 1) {
      this.setData({
        [curAnswerIndex]: 0,
      });
    } else {
      this.setData({
        [curAnswerIndex]: this.data.chatList[index].answerIndex + 1,
      });
    }
  },
  onChanged(e: any) {
    this.setData({ inputValue: e.detail });
  },
  //停止生成
  stopFn() {
    if (this.data.requestTask) {
      this.data.requestTask.abort();
      this.setData({
        requestTask: null, // 清空 requestTask
      });
      const lastIndex = this.data.chatList.length - 1;
      const lastItem = this.data.chatList[lastIndex];

      if (this.data.isRegenerate) {
        //重新生成
        const messageLast =
          "chatList[" +
          lastIndex +
          "].message[" +
          (lastItem.message.length - 1 + "]");
        const thinkListLast =
          "chatList[" +
          lastIndex +
          "].thinkList[" +
          (lastItem.message.length - 1 + "]");
        const answerListLast =
          "chatList[" +
          lastIndex +
          "].answerList[" +
          (lastItem.message.length - 1 + "]");
        const showThinkListLast =
          "chatList[" +
          lastIndex +
          "].showThinkList[" +
          (lastItem.message.length - 1 + "]");
        const downMessageLast =
          "chatList[" +
          lastIndex +
          "].downMessage[" +
          (lastItem.message.length - 1 + "]");
        const answerIndex = "chatList[" + lastIndex + "].answerIndex";
        this.setData({
          [messageLast]:
            this.data.currentHTML +
            "<div style='font-size:16px;margin-top:10px;margin-bottom:15px'>停止生成</div>",
          [thinkListLast]: this.data.currentThinkHTML,
          [answerListLast]:
            this.data.currentAnswerHTML +
            "<div style='font-size:16px;margin-top:10px;margin-bottom:15px'>停止生成</div>",
          [showThinkListLast]: true,
          [downMessageLast]:
            this.data.contentItems + "\n" + "\n" + "停止生成" + "\n",
          [answerIndex]: lastItem.message.length - 1,
        });
      } else {
        //第一次生成
        const curLastIndex = this.data.chatList.length - 1;
        const lastMessage = "chatList[" + curLastIndex + "].message";
        const lastThinkList = "chatList[" + curLastIndex + "].thinkList";
        const lastAnswerList = "chatList[" + curLastIndex + "].answerList";
        const lastShowThinkList =
          "chatList[" + curLastIndex + "].showThinkList";

        const lastDownMessage = "chatList[" + curLastIndex + "].downMessage";
        const lastIsLoading = "chatList[" + curLastIndex + "].isLoading";
        this.setData({
          [lastMessage]: [
            this.data.currentHTML +
              "<div style='font-size:16px;margin-top:10px;margin-bottom:15px'>停止生成</div>",
          ],
          [lastThinkList]: [this.data.currentThinkHTML],
          [lastAnswerList]: [
            this.data.currentAnswerHTML +
              "<div style='font-size:16px;margin-top:10px;margin-bottom:15px'>停止生成</div>",
          ],
          [lastShowThinkList]: [true],
          [lastDownMessage]: [
            this.data.contentItems + "\n" + "\n" + "停止生成" + "\n",
          ],
          [lastIsLoading]: false,
        });
      }
    }
  },
  //置顶
  handleScrollToUpper() {
    this.setData({
      scrollBottomShow: true,
    });
  },
  //置底
  handleScrollToLower() {
    this.setData({
      scrollTopShow: true,
    });
  },
  scrollTopFn() {
    this.setData({
      scrollTop: 0,
      scrollTopShow: false,
    });
  },
  scrollBottomFn() {
    this.setData({
      scrollTop: 999999,
      scrollBottomShow: false, // 设置一个足够大的值，确保滚动到底部
    });
  },
  //设置菜单
  setMenu() {
    this.setData({ visible: true });
  },
  //返回
  backFn() {
    wx.navigateBack();
  },
  //跳转人工客服
  gotoService() {
    wx.navigateTo({
      url: "/pages/mine/subpages/contactus/contactus",
    });
  },
  // 使用 marked
  markdownToHtml(markdown: string) {
    return marked(markdown)
      .replaceAll(
        "<table>",
        '<table style="width: 100%; border-collapse: collapse; margin: 10px 0;">'
      )
      .replaceAll(
        "<th>",
        '<th style="border: 1px solid #ddd; padding: 8px; text-align: left; background-color: #f2f2f2; font-weight: bold;">'
      )
      .replaceAll(
        "<td>",
        '<td style="border: 1px solid #ddd; padding: 8px; text-align: left;">'
      );
  },
  //重置操作，接口响应成功后重置数据
  resetFn() {
    const lastIsLoading =
      "chatList[" + (this.data.chatList.length - 1) + "].isLoading";
    this.setData({
      [lastIsLoading]: false,
      contentItems: "",
      isLoading: false,
      loadingStatus: false,
    });
  },
  requestFn() {
    var that = this;
    //先判断inputStr有没有值,isRegenerate表示是否重新生成
    const inputStr = that.data.isRegenerate
      ? that.data.preInputValue
      : that.data.inputValue;
    if (!inputStr)
      return wx.showToast({
        title: "请输入要查询的问题。",
        icon: "none",
      });
    if (that.data.isLoading)
      return wx.showToast({
        title: "正在生成内容,请稍后。",
        icon: "none",
      });
    that.setData({ isLoading: true });
    if (!that.data.isRegenerate) {
      let curChatList = that.data.chatList;
      //第一次生成
      that.setData({
        chatList: curChatList.concat([
          {
            type: "user",
            message: [inputStr],
            answerIndex: 0,
            isLoading: false,
            downMessage: [inputStr],
            thinkList: [],
            answerList: [],
            showThinkList: [],
          },
        ]),
      });
      that.setData({
        scrollTop: 999999, // 设置一个足够大的值，确保滚动到底部
        titleStr: that.data.chatList[0].message[0],
      });
    }
    that.setData({ loadingStatus: true });
    const cookie = wx.getStorageSync("Cookie");
    const accountInfo = wx.getAccountInfoSync();
    const env = accountInfo.miniProgram.envVersion;
    if (env === "develop" || env === "trial") {
      that.setData({
        baseUrl: "https://test-shiye.bczcc.com",
      });
    } else if (env === "release") {
      that.setData({
        baseUrl: "https://shiye.bczcc.com",
      });
    }
    const urlStr = `${that.data.baseUrl}/recheck-web/confined/shiye/chat?message=${inputStr}`;

    const requestTask = wx.request({
      url: urlStr,
      responseType: "arraybuffer",
      method: "GET",
      header: {
        Cookie: cookie,
      },
      enableChunked: true,
      //接口响应结束后执行
      success: () => {
        that.resetFn();
      },
      //响应失败后执行
      fail: () => {
        that.resetFn();
      },
      //接口响应结束后执行，晚于success阶段
      complete: () => {
        that.resetFn();
      },
    });
    //接口响应成功，但此时无内容响应，相当于fetchEventSource的open阶段
    requestTask.onHeadersReceived(function (res: any) {
      if (res.statusCode !== 200)
        if (res.statusCode === 401) {
          zcc.logout();
          wx.navigateTo({ url: "/pages/login/login" });
          return;
        } else {
          return wx.showToast({
            title: "服务器忙，请稍后再试。",
            icon: "none",
          });
        }

      //判断是否重新生成,如果重新生成向最后chatList最后一项中的message中追加,如果不是重新生成向chatList中追加一条
      if (that.data.isRegenerate) {
        const lastIndex = that.data.chatList.length - 1;
        const lastMessage = "chatList[" + lastIndex + "].message";
        const lastThinkList = "chatList[" + lastIndex + "].thinkList";
        const lastAnswerList = "chatList[" + lastIndex + "].answerList";
        const lastShowThinkList = "chatList[" + lastIndex + "].showThinkList";

        const lastDownMessage = "chatList[" + lastIndex + "].downMessage";
        const lastAnswerIndex = "chatList[" + lastIndex + "].answerIndex";
        that.setData({
          [lastMessage]: that.data.chatList[lastIndex].message.concat([""]),
          [lastThinkList]: that.data.chatList[lastIndex].thinkList.concat([""]),
          [lastAnswerList]: that.data.chatList[lastIndex].answerList.concat([
            "",
          ]),
          [lastShowThinkList]: that.data.chatList[
            lastIndex
          ].showThinkList.concat([true]),
          [lastDownMessage]: that.data.chatList[lastIndex].downMessage.concat([
            "",
          ]),
          [lastAnswerIndex]: that.data.chatList[lastIndex].answerIndex + 1,
        });
      } else {
        let curChatList = that.data.chatList.concat([
          {
            type: "ai",
            message: [],
            answerIndex: 0,
            isLoading: true,
            downMessage: [],
            reportUrl: "",
            thinkList: [],
            answerList: [],
            showThinkList: [],
          },
        ]);
        that.setData({
          chatList: curChatList,
          preInputValue: that.data.inputValue,
        });
      }
      const lastIsLoading =
        "chatList[" + (that.data.chatList.length - 1) + "].isLoading";
      that.setData({
        inputValue: "",
        isLoading: true,
        // loadingStatus: false,
        [lastIsLoading]: true,
      });
    });
    //持续内容响应，相当于fetchEventSource的onmessage阶段
    requestTask.onChunkReceived(function (r) {
      that.setData({
        loadingStatus: false,
      });
      // onChunkReceived 有可能同时接收两条信息，所以需将响应数据转化为数组
      let arr = arrayBufferToString(r.data);
      arr.forEach(async (item) => {
        if (item) {
          const content = item.content;
          await that.setData({
            contentItems: that.data.contentItems + content,
          });
          if (that.data.isBottom) {
            that.setData({
              scrollTop: 999999, // 设置一个足够大的值，确保滚动到底部
            });
          }
          if (that.data.contentItems) {
            if (that.data.contentItems.includes("</sy_think>")) {
              const arr = that.data.contentItems.split("</sy_think>");
              that.setData({
                currentThinkHTML: arr[0].replace("<sy_think>", ""),
                currentAnswerHTML: that.markdownToHtml(arr[1]),
              });
            } else {
              that.setData({
                currentThinkHTML: that.data.contentItems.replace(
                  "<sy_think>",
                  ""
                ),
                currentAnswerHTML: "",
              });
            }
            that.setData({
              currentHTML: that.data.contentItems.replace("<sy_think>", ""),
            });
          } else {
            that.setData({
              currentHTML: "",
              currentThinkHTML: "",
              currentAnswerHTML: "",
            });
          }

          if (item.status === "end") {
            const lastIndex = that.data.chatList.length - 1;
            const lastItem = that.data.chatList[lastIndex];
            if (that.data.isRegenerate) {
              //重新生成
              const messageLast =
                "chatList[" +
                lastIndex +
                "].message[" +
                (lastItem.message.length - 1 + "]");
              const thinkListLast =
                "chatList[" +
                lastIndex +
                "].thinkList[" +
                (lastItem.message.length - 1 + "]");
              const answerListLast =
                "chatList[" +
                lastIndex +
                "].answerList[" +
                (lastItem.message.length - 1 + "]");
              const showThinkListLast =
                "chatList[" +
                lastIndex +
                "].showThinkList[" +
                (lastItem.message.length - 1 + "]");
              const downMessageLast =
                "chatList[" +
                lastIndex +
                "].downMessage[" +
                (lastItem.message.length - 1 + "]");
              const answerIndex = "chatList[" + lastIndex + "].answerIndex";
              that.setData({
                [messageLast]: that.data.currentHTML,
                [thinkListLast]: that.data.currentThinkHTML,
                [answerListLast]: that.data.currentAnswerHTML,
                [showThinkListLast]: true,
                [downMessageLast]: that.data.contentItems,
                [answerIndex]: lastItem.message.length - 1,
              });
            } else {
              //第一次生成
              const curLastIndex = that.data.chatList.length - 1;
              const lastMessage = "chatList[" + curLastIndex + "].message";
              const lastThinkList = "chatList[" + curLastIndex + "].thinkList";
              const lastAnswerList =
                "chatList[" + curLastIndex + "].answerList";
              const lastShowThinkList =
                "chatList[" + curLastIndex + "].showThinkList";

              const lastDownMessage =
                "chatList[" + curLastIndex + "].downMessage";
              const lastIsLoading = "chatList[" + curLastIndex + "].isLoading";
              that.setData({
                [lastMessage]: [that.data.currentHTML],
                [lastThinkList]: [that.data.currentThinkHTML],
                [lastAnswerList]: [that.data.currentAnswerHTML],
                [lastShowThinkList]: [true],
                [lastDownMessage]: [that.data.contentItems],
                [lastIsLoading]: false,
              });
            }
            that.setData({
              scrollTop: 999999, // 设置一个足够大的值，确保滚动到底部
            });
            if (item.reportUrl) {
              const lastReportUrl = "chatList[" + lastIndex + "].reportUrl";
              that.setData({
                [lastReportUrl]: item.reportUrl,
              });
            }
            that.resetFn();
          }
        }
      });
    });
    that.setData({
      requestTask: requestTask,
    });
  },
  //发送问题
  sendFn() {
    this.setData({
      isRegenerate: false,
    });
    this.requestFn();
  },
  onKeyboardShow(height: number) {
    // 处理键盘弹起逻辑
    this.setData({
      inputBoxBottom: height,
    });
  },
  onKeyboardHide() {
    // 处理键盘收起逻辑
    this.setData({
      inputBoxBottom: 0,
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: any) {
    if (options && options.question) {
      this.setData({
        inputValue: options.question,
      });
      this.requestFn();
    }
    wx.onKeyboardHeightChange((res) => {
      const height = res.height;
      if (height > 0) {
        this.onKeyboardShow(height);
      } else {
        this.onKeyboardHide();
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    if (this.data.requestTask && !this.data.loadingStatus) {
      //内容持续输出
      this.stopFn();
    } else if (this.data.requestTask && this.data.loadingStatus) {
      this.data.requestTask.abort();
      this.setData({
        requestTask: null, // 清空 requestTask
      });
      if (!this.data.isRegenerate) {
        let curChatList = this.data.chatList;
        //第一次生成
        this.setData({
          chatList: curChatList.concat([
            {
              type: "ai",
              message: ["停止生成"],
              answerIndex: 0,
              isLoading: false,
              downMessage: ["停止生成"],
              thinkList: [],
              answerList: [
                "<div style='font-size:16px;margin-top:10px;margin-bottom:15px'>停止生成</div>",
              ],
              showThinkList: [false],
            },
          ]),
          preInputValue: this.data.inputValue,
        });
      } else {
        const lastIndex = this.data.chatList.length - 1;
        const lastItem = this.data.chatList[lastIndex];
        //重新生成
        const messageLast =
          "chatList[" +
          lastIndex +
          "].message[" +
          (lastItem.message.length - 1 + "]");
        const thinkListLast =
          "chatList[" +
          lastIndex +
          "].thinkList[" +
          (lastItem.message.length - 1 + "]");
        const answerListLast =
          "chatList[" +
          lastIndex +
          "].answerList[" +
          (lastItem.message.length - 1 + "]");
        const showThinkListLast =
          "chatList[" +
          lastIndex +
          "].showThinkList[" +
          (lastItem.message.length - 1 + "]");
        const downMessageLast =
          "chatList[" +
          lastIndex +
          "].downMessage[" +
          (lastItem.message.length - 1 + "]");
        const answerIndex = "chatList[" + lastIndex + "].answerIndex";
        this.setData({
          [messageLast]:
            "<div style='font-size:16px;margin-top:10px;margin-bottom:15px'>停止生成</div>",
          [thinkListLast]: "",
          [answerListLast]:
            "<div style='font-size:16px;margin-top:10px;margin-bottom:15px'>停止生成</div>",
          [showThinkListLast]: false,
          [downMessageLast]: "\n" + "\n" + "停止生成" + "\n",
          [answerIndex]: lastItem.message.length - 1,
        });
      }
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {},
});
